<template>
  <div id="map">
    <a>
      <div id="switch"
           v-on:click="switchLayer"
           :class="{bg1:base1,bg2:base2}"></div>
    </a>
    <!-- <div id="layeron">
      <el-switch v-model="layrstatus"
                 active-color="#13ce66"
                 inactive-color="#DDDDDD"
                 @change="showLayer($event)"></el-switch>
    </div> -->
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import {
  Fill,
  Icon,
  Stroke,
  Style,
  Text,
  Circle as CircleStyle
} from "ol/style.js";
import {
  Tile as TileLayer,
  Vector as VectorLayer,
  Image as ImageLayer
} from "ol/layer";
import VectorSource from "ol/source/Vector.js";
import Feature from "ol/Feature.js";
import { fromLonLat } from "ol/proj.js";
import Point from "ol/geom/Point.js";
import Polygon from "ol/geom/Polygon.js";
import XYZ from "ol/source/XYZ";
import OSM from "ol/source/OSM.js";
import TileWMS from "ol/source/TileWMS";
import ImageWMS from "ol/source/ImageWMS";
import ImageArcGISRest from "ol/source/ImageArcGISRest";
import VectorTileLayer from "ol/layer/VectorTile.js";
import VectorTileSource from "ol/source/VectorTile.js";
import Projection from "ol/proj/Projection";
export default {
  data () {
    return {
      layrstatus: 0,
      projection: new Projection({
        code: "EPSG:4326",
        units: "degrees",
        axisOrientation: "neu",
        global: true
      }),
      center: [111, 31],
      format: "image/png",
      map: null,
      mpadbc: new TileLayer({
        source: new OSM({
          url: "http://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png" //osm地形
        }),
        projection: "EPSG:4326"
      }),
      basemap: new TileLayer({
        source: new XYZ({
          url: "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=76d35ea95dafb0023ee631a25e260ec4" //天地图影像
        }),
        projection: "EPSG:4326"
      }),
      annotion: new TileLayer({
        title: "天地图文字标注",
        source: new XYZ({
          url: "http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=76d35ea95dafb0023ee631a25e260ec4"
        })
      }),
      lyrs: [],
      zoomnum: 15,
      pointlyr: null,
      polygon: null,
      data: null,
      base1: true,
      base2: false
    };
  },
  created () {
    this.updateParams();
  },
  mounted () {
    this.initMap();
  },
  methods: {
    /**
     * 初始化底图
     */
    initMap () {
      debugger;
      let data = this.$route.query.value;
      if (data) {
        // if (data.l_on_lat != 'null' || data.l_on_lat ==) {
        //   var l_on_lon = data.l_on_lon;
        //   var l_on_lat = data.l_on_lat;
        //   var r_d_lon = data.r_d_lon;
        //   var r_d_lat = data.r_d_lat;
        //   this.polygon = this.createPolygon(
        //     l_on_lat, //x1
        //     l_on_lon,  //y1
        //     r_d_lat, //x2
        //     r_d_lon  //y2
        //   );
        // } else 
        if (data.cen_lon != null) {
          var cen_lon = data.cen_lon;
          var cen_lat = data.cen_lat;
          this.center = [cen_lon, cen_lat];
          this.pointlyr = this.createPoint(cen_lon, cen_lat);
        } else {
          console.log("不参与绘制");
        }
      } else {
        console.log("nothing!!!");
      }
      var tianditu = new TileLayer({
        source: new XYZ({
          url: "http://t4.tianditu.cn/DataServer?T=img_w&X={x}&Y={y}&L={z}" //天地图影像
        }),
        projection: "EPSG:4326"
      });
      var _view = new View({
        projection: this.projection,
        center: this.center,
        zoom: this.zoomnum
      });
      this.lyrs = [this.mpadbc, this.annotion];
      this.map = new Map({
        target: "map",
        layers: this.lyrs,
        view: _view
      });
      if (this.pointlyr) {
        this.map.addLayer(this.pointlyr);
      } else if (this.polygon) {
        this.map.addLayer(this.polygon);
      }
    },
    /**
     * 更新参数
     */
    updateParams () {
      this.data = this.$route.query.value;
    },
    /**
     * 创建点
     */
    createPoint (lon, lat) {
      var iconFeature = new Feature({
        geometry: new Point([lon, lat]),
        name: "Null Island",
        population: 4000,
        rainfall: 500
      });
      var iconStyle = new Style({
        image: new Icon(
          /** @type {module:ol/style/Icon~Options} */({
            anchor: [0.5, 46],
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            src: "../../../static/img/icon.png"
          })
        )
      });
      iconFeature.setStyle(iconStyle);
      var vectorSource = new VectorSource({
        features: [iconFeature]
      });
      var vectorLayer = new VectorLayer({
        source: vectorSource
      });
      return vectorLayer;
    },
    /**
     * 创建面
     */
    createPolygon (x1, y1, x2, y2) {
      var style = {
        Polygon: new Style({
          stroke: new Stroke({
            color: "blue",
            lineDash: [4],
            width: 3
          }),
          fill: new Fill({
            color: "rgba(0, 255, 255, 0.1)"
          })
        })
      };
      // debugger;
      var p1 = new fromLonLat([y1, x1], "EPSG:4326");
      var p2 = new fromLonLat([y2, x1], "EPSG:4326");
      var p3 = new fromLonLat([y2, x2], "EPSG:4326");
      var p4 = new fromLonLat([y1, x2], "EPSG:4326");
      var polygon = new Polygon([[p1, p2, p3, p4, p1]])
      var polyFeature = new Feature({
        geometry: polygon
      });
      var vectorSource = new VectorSource({
        features: [polyFeature],
        zIndex: 10000
      });
      var vectorLayer = new VectorLayer({
        source: vectorSource
      });
      return vectorLayer;
    },
    /**
     * 底图切换
     */
    switchLayer () {
      this.base1 = !this.base1;
      this.base2 = !this.base2;
      var layers = this.map.getLayers().array_;
      if (layers.length == 2) {
        let anno = layers[1];
        let tile = layers[0];
        this.map.removeLayer(anno);
        this.map.removeLayer(tile);
        if (this.base1) {
          this.map.addLayer(this.mpadbc);
          this.map.addLayer(this.annotion);
        } else {
          this.map.addLayer(this.basemap);
          this.map.addLayer(this.annotion);
        }
      } else if (layers.length >= 3) {
        let vectlyr = layers[2];
        let anno = layers[1];
        let tile = layers[0];
        this.map.removeLayer(vectlyr);
        this.map.removeLayer(anno);
        this.map.removeLayer(tile);
        // layers.forEach(element => {
        //   this.map.removeLayer(element)
        // });
        // for(let i = 0;i<layers.length;i++){
        //   this.map.removeLayer(layers[i])
        // }
        if (this.base1) {
          this.map.addLayer(this.mpadbc);
          this.map.addLayer(this.annotion);
        } else {
          this.map.addLayer(this.basemap);
          this.map.addLayer(this.annotion);
        }
        this.map.addLayer(vectlyr);
      }
    },
    /**
     * 打开图层
     */
    showLayer (val) {
      // debugger
      let data = this.$route.query.value;
      var layer = null;
      if (data) {
        let sname = data.sname;
        layer = new ImageLayer({
          extent: this.bounds,
          source: new ImageWMS({
            ratio: 1,
            url: "http://localhost:8090/geoserver/cite/wms",
            params: {
              VERSION: "1.1.1",
              STYLES: "",
              LAYERS: "cite:" + sname,
              exceptions: "application/vnd.ogc.se_inimage"
            }
          })
        });
      }
      var layers = this.map.getLayers().array_;
      var len = layers.length;
      var layer_last = layers[len - 1]
      if (layer != null) {
        if (this.layrstatus == true) {
          this.layrstatus == false;
          this.map.removeLayer(layer);
          this.map.addLayer(layer);
        } else {
          this.layrstatus == true;
          this.map.removeLayer(layer_last);
        }
      }
    }
  }
};
</script>

<style scoped>
#layeron {
  position: absolute;
  top: 50px;
  right: 130px;
  z-index: 9999;
}
#switch {
  z-index: 999;
  height: 80px;
  width: 80px;
  position: absolute;
  right: 30px;
  margin: 10px;
  top: 40px;
  padding: 10px;
  border: 2px solid #242f42;
  border-radius: 5px;
}
.bg1 {
  background-image: url(../../../static/img/map.png);
}
.bg2 {
  background-image: url(../../../static/img/satelite.png);
}
h1 {
  text-align: center;
  margin: 30px 0;
}
p {
  line-height: 30px;
  margin-bottom: 10px;
  text-indent: 2em;
}
.logout {
  color: #409eff;
}
</style>